package login

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	businessError "sg-backend/error"
	"sg-backend/global"
	"sg-backend/model/user"
	"sg-backend/utils"
)

type PasswordChangeDto struct {
	Password1 string `json:"password1"`
	Password2 string `json:"password2"`
}

// FirstLoginChangPassword 初次登录强制修改密码
func FirstLoginChangPassword(c *fiber.Ctx) error {
	var passwordDto PasswordChangeDto
	if err := c.BodyParser(&passwordDto); err != nil {
		panic(businessError.New(businessError.BAD_REQUEST))
	}

	// 判断密码是否相等
	if passwordDto.Password1 != passwordDto.Password2 {
		return c.JSON(fiber.Map{
			"status":  "error",
			"message": "两次输入的密码不一致，请确认！",
		})
	}

	// 获取用户对象
	u := user.User{Id: global.AuthUser.UserId}
	r := global.DB.First(&u)
	if r.Error != nil {
		return c.JSON(fiber.Map{
			"status":  "error",
			"message": fmt.Sprintf("修改密码出错，获取不到用户对象！%v", r.Error),
		})
	}

	// 生成新密码
	var passwordSalt = utils.GetRandomString(16)
	var encryptPassword = utils.SHAEncrypt(passwordDto.Password1 + passwordSalt)

	// 保存到数据库
	u.PasswordSalt = passwordSalt
	u.Password = encryptPassword
	u.IsFirstLogin = false
	r = global.DB.Save(&u)
	if r.Error != nil {
		return c.JSON(fiber.Map{
			"status":  "error",
			"message": fmt.Sprintf("修改密码出错，保存到数据库出错！%v", r.Error),
		})
	}
	fmt.Println("保存后的密码：", u.Password, u.PasswordSalt)
	// 返回成功结果
	return c.JSON(fiber.Map{
		"success": true,
		"status":  "done",
		"message": "密码修改成功，请重新登录！",
	})
}
